import { Component, OnInit } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { TableStyleService, TableStyle } from 'src/app/service/table-style.service';
import { JsonResult } from 'src/app/model/JsonResult';
import { RoadTrip, RoadTripService } from 'src/app/service/road-trip.service';
import { VariableService } from 'src/app/service/variable.service';
import { isDate } from 'util';
import * as gc from 'src/app/global/const';
import { UUID } from 'angular2-uuid';
import { BreadFieldService } from 'src/app/service/bread-field.service';

@Component({
  selector: 'app-road-trip',
  templateUrl: './road-trip.component.html',
  styleUrls: ['./road-trip.component.css'],
})
export class RoadTripComponent implements OnInit {
  
  vari:{
    'tableName':string,
    'tableData':RoadTrip[],
    'mouseOver_rowIndex':number,
    'emptyRowCount':number, // 空白行数
    'statistics':{ [key:string]:{value:number,label:string} }
  } = { 'tableName':'road_trip','tableData':[],mouseOver_rowIndex:-1,'emptyRowCount':1,
    'statistics':{}};


  opts_req:{
    'tableStyle':TableStyle[]
  } = { 'tableStyle':[] };

  opts_enum:{ [key:string]:{label:string,value:number}[] } = {};

  cache:{
    detail:{ [key:string]:{ edit:boolean,data:RoadTrip } }
  } = {
    'detail':{}
  }

  aaa:string = '1';
  mouseOverUUID:string= '';


  constructor(
    private noti:NzNotificationService,
    private tableStyleService:TableStyleService,
    private detailService:RoadTripService,
    private breadField:BreadFieldService
  ) { 
    this.init();
  }

  ngOnInit() {
  }

  init(){
    this.initOpts();
    this.pullTableData();
    
  }

  updateEditCache(){
    // 更新表格编辑缓存数据
    this.vari.tableData.forEach(
      (ele:RoadTrip) => {
        this.cache.detail[ele.uuid] = {
          edit:false,data:{...ele}
        }
    });
    
  }

  // 初始化获取所有带选择数据和字段样式数据
  initOpts(){
    this.tableStyleService.selectByTableName(this.vari.tableName).subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg(res.msg);
          return
        }

        let styleData:TableStyle[] = res.data;
        styleData.forEach(ele => {
          if( ele.width_percent>0 )
            ele.width_percent_str = ele.width_percent + 'px';
          this.resolveEnumOpts(ele);
        });
        this.opts_req.tableStyle = styleData;
        console.log('表格样式数据是：');
        console.log(this.opts_req.tableStyle);
      },error => this.msg('获取表格样式数据时出现异常！')
    )
  }

  // 刷新表格数据
  pullTableData(){
    this.detailService.selectAll().subscribe(
      ( res:JsonResult ) =>{
        if( res.code !== 1 ){
          this.msg(res.msg);
          return
        }

        this.vari.tableData = res.data;
        this.updateEditCache();// 更新编辑用缓存数据
        // this.buildEmptyRows();
        this.updateStatistics();// 更新统计数据
      },error => this.msg('获取表格数据时出现异常！')
    )
  }

  // 构建空白行
  buildEmptyRows(){
    if( this.vari.emptyRowCount === undefined ||this.vari.emptyRowCount === null || this.vari.emptyRowCount<=0 ) return

    let emptyRows:RoadTrip[] = [];
    let lastUUID:string = '';
    for(let i=0;i<this.vari.emptyRowCount;i++){
      let newRecord = new RoadTrip();
      lastUUID = newRecord.uuid;
      emptyRows.push(newRecord); 
    }

    this.vari.tableData = this.vari.tableData.concat(emptyRows);
    this.updateEditCache();
    this.cache.detail[lastUUID].edit = true;
  }


  /**
   * 解析来自数据库端的枚举类型的选项，构建为本地数组
   * @param enums 格式为：value1=label1,value2=label2
   */
  resolveEnumOpts(record:TableStyle){
    let enums = record.opts;
    if( enums === undefined || enums === null || enums.length<=0 ) {
      return
    }
    if( record.immutable === true ) return // 是系统字段则不构建

    let arr = enums.split(',');
    let ret:{label:string,value:number}[] = [];
    arr.forEach(ele => {
      let val = ele.split('=');
      ret.push({ value:parseInt(val[0]),label:val[1] });
    });

    this.opts_enum[record.field_name] = ret;
  }


  msg(content:string){
    this.noti.blank('通知',content);
  }

  printOpts(){
    console.log(this.opts_enum['one_way']);
  }

  getOptsEnum(fieldName:string):any[]{
    return this.opts_enum[fieldName];
  }

  mouseOver(uuid:string){
    // this.mouseOverUUID = uuid;
  }

  mouseLeave(rowIndex:number){
    //this.msg('鼠标走开了 --- ' + rowIndex);
  }

  /**
   * 新增一个空行，并且处于编辑状态
   */
  addEmptyRow(){
     let record:RoadTrip = new RoadTrip();
     let uuid:string = record.uuid;
     this.cache.detail[uuid] = {
       edit:true,data:record
     };

    //  let ret = this.vari.tableData.splice(this.vari.tableData.length,0,record);
     this.vari.tableData = this.vari.tableData.concat(record);
  }


  printTableData(){
    console.log(this.vari.tableData);
  }

  hasEditableRow():boolean{
    let data = this.cache.detail;
    if( data === undefined || data === null ) return false;

    for(let attr in this.cache.detail){
      if( this.cache.detail[attr].edit )
        return true;
    }

    return false;
  }

  startEdit(rowIndex:number,uuid:string,event){
    event.preventDefault();
    this.cache.detail[uuid].edit = true;
    // this.fillDefault(rowIndex,uuid);
    // this.msg('开启编辑状态的行是：' + rowIndex + ',' + uuid);
  }

  cancelEdit(rowIndex:number,uuid:string){
    this.cache.detail[uuid].edit = false;
  }

  saveEdit(rowIndex:number,uuid:string){
    let record:RoadTrip = this.cache.detail[uuid].data;
    this.detailService.saveOne(record).subscribe(
      ( res:JsonResult ) => {
        if( res.code !=1 ){
          this.msg(res.msg);
          return
        }

        this.msg('保存完毕！');
        let newArray = this.vari.tableData.filter(
          item => item.uuid !== uuid
        )
        let newRecord:RoadTrip = res.data;
        newRecord.uuid = UUID.UUID();
        newArray.splice(rowIndex,0,{...newRecord})
        this.vari.tableData = newArray;
        this.updateEditCache();// 更新编辑用缓存数据
        this.updateStatistics();// 更新统计数据
        this.cache.detail[newRecord.uuid].edit = false;
      },error => this.msg('保存时出现异常！')
    )

  }

  // 删除行 - 仅前端
  deleteRow_front(rowIndex:number,uuid:string){
    this.vari.tableData = this.vari.tableData.filter(
      item => item.uuid !== uuid
    )
  }
  
  /**
   * 删除一行数据：
   * 1. 如果没有iid ，那么只要删除前端 + 更新编辑用缓存数据
   * 2. 删除后端成功后，删除前端 + 更新编辑用缓存数据
   * @param rowIndex 行序号，从0开始
   * @param uuid 行属性uuid
   */
  deleteRow(rowIndex:number,uuid:string){
    let iid = this.vari.tableData[rowIndex].iid;
    if( iid === undefined || iid === null || iid<=0 ){// 仅仅删除前端
      this.deleteRow_front(rowIndex,uuid);
      this.updateEditCache();
      this.updateStatistics();
    }else{// 删除后端成功后：删除前端 + 更新编辑用缓存
      this.detailService.deleteByPrimaryKey(this.vari.tableData[rowIndex].iid).subscribe(
        ( res:JsonResult ) => {
          if( res.code != 1 ){
            this.msg(res.msg);
            return
          }
  
          this.deleteRow_front(rowIndex,uuid);
          this.updateEditCache();
          this.updateStatistics();
          this.msg('删除完毕！');
        },error => this.msg('删除时出现异常！')
      )
    }
  }

  cancelDeleteRow(){
    console.log('取消了删除行');
  }

  copyRow(rowIndex:number,uuid:string){
    let iid = this.vari.tableData[rowIndex].iid;
    if( iid === undefined || iid === null || iid <=0 ){
      this.msg('该行还未保存，不可复制！');
      return
    }

    let newRecord:RoadTrip = {...this.vari.tableData[rowIndex]};
    newRecord.iid = 0;
    this.detailService.insert(newRecord).subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg(res.msg);
          return
        }

        newRecord.uuid = UUID.UUID();
        this.vari.tableData = this.vari.tableData.concat(newRecord);
        this.updateEditCache();
        this.msg('复制完毕！');
      },error => this.msg('复制时出现异常！')
    )
  }


/**
 * 将数据库 table_style 表中设置为枚举类型的下拉选项的字段
 * 显示为其值对应的文本
 * @param record 行数据，单个实体类对象
 * @param fieldName 字段名称
 */
  convertRaw2Show(record:RoadTrip,tsRow:TableStyle):string{
    return this.breadField.convertRaw2Show(record,tsRow);
  }


  // 为下拉控件填充默认值
  fillDefault(rowIndex:number,uuid:string){
    console.log('进入fillDefault');
    this.opts_req.tableStyle.forEach(ele => {
      switch(ele.ctl_type){
        case('optsEnum'):
          console.log('是 optsEnum 类型的控件，赋值前：' + this.cache.detail[uuid].data[ele.field_name]);
          this.cache.detail[uuid].data[ele.field_name] = this.vari.tableData[rowIndex][ele.field_name];
          console.log('赋值后：' + this.cache.detail[uuid].data[ele.field_name]);
          break;
        default:
          break;
      }
    });
    
  }

  setTest(){
    let aa:string = '1+2-3*4/2';
    const gg = /\+|\-|\*|\//g;
    let bb = aa.split(gg);

    console.log(bb);
  }

  generateCol(dataRow:RoadTrip,tsRow:TableStyle){
    return this.breadField.getGeneratedResult(dataRow,tsRow);
  }

  colHeaderAlign(fieldName:string):string{
    let tsRow:TableStyle = this.opts_req.tableStyle.filter( item => item.field_name === fieldName )[0];
    return tsRow.align_header;
  }

  colContentAlign(fieldName:string):string{
    let tsRow:TableStyle = this.opts_req.tableStyle.filter( item => item.field_name === fieldName )[0];
    return tsRow.align_cell;
  }

  // 更新统计数据
  updateStatistics(){
    if( this.vari.tableData.length<=0 ){
      this.msg('表格数据为空，无法统计数量！');
      return
    }

    this.vari.statistics = null;
    this.vari.statistics = {};

    // 遍历字段构建汇总对象
    let arr = this.opts_req.tableStyle.filter(item=>item.statistics);
    if( arr.length<=0 ) {
      this.msg('没有需要统计的字段！');
      return
    }

    console.log('需要统计的字段有：');
    console.log(arr);
    arr.forEach(ele => {
      this.vari.statistics[ele.field_name] = { value:0,label:'' };
    });
    

    this.vari.tableData.forEach(ele => {
      this.opts_req.tableStyle.forEach(ele1 => {
        let field:string = ele1.field_name;
        if( ele1.statistics ){
          let curValue:number = ele[field] === undefined?0:ele[field];
          curValue = curValue === null?0:curValue;
          this.vari.statistics[field].value = this.vari.statistics[field].value + curValue;
          this.vari.statistics[field].label = Number(this.vari.statistics[field].value).toFixed(1);
        }
      });
    });
  }


  refreshTable(){
    this.pullTableData();
  }


  resolveFormula(dataRow:RoadTrip,tsRow:TableStyle):string{
    if( !tsRow.statistics ) return

    return this.breadField.useFormatter(dataRow,tsRow)
  }

  inputChange(dataRow:RoadTrip,tsRow:TableStyle){
    let arr:{ fieldName:string,value:number }[] = this.breadField.triggerFormula(dataRow,tsRow,this.opts_req.tableStyle);
    if( arr.length<=0 ) return
    arr.forEach(ele => {
      this.cache.detail[dataRow.uuid].data[ele.fieldName] = ele.value;
    });
  }

}
